//
//  DDBossOnlineInterviewAlert.m
//  DingDongZP
//
//  Created by 杨政涛 on 16/11/3.
//  Copyright © 2016年 51ledian.com. All rights reserved.
//

#import "DDBossOnlineInterviewAlert.h"
#import <BlocksKit/BlocksKit.h>
#import "DDCustomLabel.h"

@interface DDBossOnlineInterviewAlert ()<RCCallSessionDelegate>

@property (nonatomic, strong)RCCallSingleCallViewController *callViewPre;
@property (nonatomic, strong)RCCallSingleCallViewController *callView;

@end

@implementation DDBossOnlineInterviewAlert

NSDictionary *responseObjectMessage;
NSTimer *timer;

+ (instancetype)shareManager
{
    static DDBossOnlineInterviewAlert *manager = nil;
    
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        manager = [[self alloc] init];
    });
    
    return manager;
}

/**
 *  Boss用户收到在线面试时候查询的面试计价规则
 */
- (void)queryInterviewRlues
{
    
    DDIntervitedService *intervitedService = [[DDIntervitedService alloc]init];
    [intervitedService postInterviewRulesSuccessBlock:^(id responseObject) {
        
        responseObjectMessage = responseObject;
        [self performSelectorOnMainThread:@selector(backToMain) withObject:self waitUntilDone:YES];
        
    } failBlock:nil];
    
    
}

- (void)backToMain
{
    
    DDInterviewRuleModel *interviewRuleModel = [DDInterviewRuleModel sharedManager];
    interviewRuleModel = [DDInterviewRuleModel yy_modelWithJSON:responseObjectMessage[@"data"]];
    /**
     *  账户余额不足  提示
     */
    if (interviewRuleModel.money<interviewRuleModel.min_money) {

        
        UIAlertController *alert = [UIAlertController alertControllerWithTitle:nil message:@"" preferredStyle:UIAlertControllerStyleAlert];
        
        UIAlertAction *cancelAction = [UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:^(UIAlertAction * _Nonnull action) {
            /**
             *  挂断视频通话
             */
            [[RCCall sharedRCCall].currentCallSession hangup];
        }];
        
        UIAlertAction *defaultAction = [UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
            /**
             *  挂断视频通话
             */
            [[RCCall sharedRCCall].currentCallSession hangup];
            
            [self bk_performBlock:^(id obj) {
                
                [[NSOperationQueue mainQueue] addOperationWithBlock:^{
                    /**
                     *  跳转充值页面
                     */
                    UITabBarController *tabVC = (UITabBarController *)[[[UIApplication sharedApplication] keyWindow ] rootViewController];
                    UINavigationController *nav = tabVC.viewControllers[tabVC.selectedIndex];
                    
                    DDPayViewController *payVC = [[DDPayViewController alloc]init];
                    [nav pushViewController:payVC animated:true];
                }];
                
            } afterDelay:1];
        }];

        //修改message
        DDCustomLabel *label = [[DDCustomLabel alloc] init];
        label.textColor = COLOR_FONT_BLACK;
        label.text = [NSString stringWithFormat:@"您好，您的账户余额为%0.2f元。在线面试服务资费为：%@元/分钟，账户保底金额为%0.0f元。请前往充值页面进行充值。",interviewRuleModel.money,interviewRuleModel.price,interviewRuleModel.min_money];
        [label setAttributeLabelWithtextColorPairs:@[@{[NSString stringWithFormat:@"%0.2f",interviewRuleModel.money]:COLOR_FONT_RED},@{[NSString stringWithFormat:@"%@",interviewRuleModel.price]:COLOR_FONT_RED},@{[NSString stringWithFormat:@"%0.0f",interviewRuleModel.min_money]:COLOR_FONT_RED}]];
        
        [alert setValue:label.attributedText forKey:@"attributedMessage"];
        
        //修改按钮颜色
        [cancelAction setValue:COLOR_FONT_RED forKey:@"titleTextColor"];
        [defaultAction setValue:COLOR_FONT_ALERTGREEN forKey:@"titleTextColor"];

        [alert addAction:cancelAction];
        [alert addAction:defaultAction];
   
        id tabVC = (UITabBarController *)[[[UIApplication sharedApplication] keyWindow ] rootViewController];
        [tabVC presentViewController:alert animated:YES completion:nil];
    }
}


/**
 *  Boss用户在点击在线面试的时候查询的面试计价规则
 */
- (void)queryInterviewRluesBeforeSelectOnlineInterview
{
    
    DDIntervitedService *intervitedService = [[DDIntervitedService alloc]init];
    [intervitedService postInterviewRulesSuccessBlock:^(id responseObject) {
        
        responseObjectMessage = responseObject;
        [self performSelectorOnMainThread:@selector(backToMainTwo) withObject:self waitUntilDone:YES];
        
    } failBlock:nil];
    
}

- (void)backToMainTwo
{
    DDInterviewRuleModel *interviewRuleModel = [DDInterviewRuleModel sharedManager];
    interviewRuleModel = [DDInterviewRuleModel yy_modelWithJSON:responseObjectMessage[@"data"]];
    /**
     *  账户余额不足  提示
     */
    if (interviewRuleModel.money<interviewRuleModel.min_money) {
        
        UIAlertController *alert = [UIAlertController alertControllerWithTitle:nil message:@"" preferredStyle:UIAlertControllerStyleAlert];
        
        UIAlertAction *cancelAction = [UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:nil];
        
        UIAlertAction *defaultAction = [UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
          
        [[NSOperationQueue mainQueue] addOperationWithBlock:^{
                            /**
                             *  跳转充值页面
                             */
        UITabBarController *tabVC = (UITabBarController *)[[[UIApplication sharedApplication] keyWindow ] rootViewController];
        UINavigationController *nav = tabVC.viewControllers[tabVC.selectedIndex];
            
        DDPayViewController *payVC = [[DDPayViewController alloc]init];
        [nav pushViewController:payVC animated:true];
                          }];
            
        }];
        
        //修改message
        DDCustomLabel *label = [[DDCustomLabel alloc] init];
        label.textColor = COLOR_FONT_BLACK;
        label.text = [NSString stringWithFormat:@"您好，您的账户余额为%0.2f元。在线面试服务资费为：%@元/分钟，账户保底金额为%0.0f元。请前往充值页面进行充值。",interviewRuleModel.money,interviewRuleModel.price,interviewRuleModel.min_money];
        [label setAttributeLabelWithtextColorPairs:@[@{[NSString stringWithFormat:@"%0.2f",interviewRuleModel.money]:COLOR_FONT_RED},@{[NSString stringWithFormat:@"%@",interviewRuleModel.price]:COLOR_FONT_RED},@{[NSString stringWithFormat:@"%0.0f",interviewRuleModel.min_money]:COLOR_FONT_RED}]];
        
        [alert setValue:label.attributedText forKey:@"attributedMessage"];
        
        //修改按钮颜色
        [cancelAction setValue:COLOR_FONT_RED forKey:@"titleTextColor"];
        [defaultAction setValue:COLOR_FONT_ALERTGREEN forKey:@"titleTextColor"];
        
        [alert addAction:cancelAction];
        [alert addAction:defaultAction];
        
        
        UITabBarController *tabVC = (UITabBarController *)[[[UIApplication sharedApplication] keyWindow ] rootViewController];
        UINavigationController *nav = tabVC.viewControllers[tabVC.selectedIndex];
        [nav presentViewController:alert animated:YES completion:nil];
        
    }else{
        
        self.callViewPre = [[RCCallSingleCallViewController alloc]initWithOutgoingCall:self.targetID mediaType:RCCallMediaVideo];
        [[RCCall sharedRCCall]presentCallViewController:self.callViewPre];
        
        [[RCCallClient sharedRCCallClient] startCall:ConversationType_PRIVATE targetId:self.targetID to:@[self.targetID] mediaType:RCCallMediaVideo sessionDelegate:nil extra:nil];
        [[RCCall sharedRCCall].currentCallSession setDelegate:self];
    }
}


/**
 * Boss 动态发起一个在线面试  并对其进行扣费
 */
- (void)creatInterviewAndFeededuction
{
    /**
     *   动态发起一个在线面试
     */
    DDIntervitedService *intervitedService = [[DDIntervitedService alloc]init];
    
    NSDate *currentDate = [NSDate date];//获取当前时间，日期
    NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
    [dateFormatter setDateFormat:@"YYYY-MM-dd HH:mm"];
    NSString *dateString = [dateFormatter stringFromDate:currentDate];
    
    //state  状态：1　面试发起 2被拒绝  3同意面试 4面试取消 5面试结束 6已经扣费
    [intervitedService sendInterviewType:@"2" withState:@"3" withInterViewID:@"" withJob_id:self.jobID withEmplyoer_id:self.emplyoerID withJobfinder_id:self.jobfinderID withInterviewdt:dateString withLink_mobile:@"" withAddress:@"" withRemark:@"" SuccessBlock:^(id responseObject) {
        
        self.interviewSendResult = responseObject[@"msg"];
        
        if ([self.interviewSendResult isEqualToString:@"成功！"]) {
            
            self.interviewid = responseObject[@"data"][@"id"];
        }
        
        [self performSelectorOnMainThread:@selector(backToMainThree) withObject:self waitUntilDone:YES];
        
    } failBlock:nil];
    
}

//返回主线程  进行网络请求扣费
- (void)backToMainThree
{
    
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(onlineInterviewEnd) name:NOTI_OnlineInterview_END object:nil];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(onlineInterviewError) name:NOTI_OnlineInterview_ERROR object:nil];
    
    if ([self.interviewSendResult isEqualToString:@"成功！"]){
        
        
        DDIntervitedService *intervitedService = [[DDIntervitedService alloc]init];
        [intervitedService prePayInterviewWithInterviewID:self.interviewid SuccessBlock:^(id responseObject) {
            
        } failBlock:nil];
        
        /**
         * 定时器  每分钟循环扣费一次
         */
        timer = [NSTimer timerWithTimeInterval:60 target:self selector:@selector(feededuction) userInfo:nil repeats:YES];
        [[NSRunLoop mainRunLoop] addTimer:timer forMode:NSDefaultRunLoopMode];
    }
}

- (void)feededuction
{
    
    
    DDIntervitedService *intervitedService = [[DDIntervitedService alloc]init];
    [intervitedService prePayInterviewWithInterviewID:self.interviewid SuccessBlock:^(id responseObject) {
        
    } failBlock:nil];
    
}

- (void)onlineInterviewEnd
{
    
    [timer invalidate];
}

- (void)onlineInterviewError
{
    [timer invalidate];
}

#pragma mark-视频通话代理方法

- (void)callDidConnect
{
    [[UIDevice currentDevice] setProximityMonitoringEnabled:YES];
    
    [[RCCall sharedRCCall]dismissCallViewController:self.callViewPre];
    
    self.callView = [[RCCallSingleCallViewController alloc]initWithActiveCall:[RCCall sharedRCCall].currentCallSession];
    [[RCCall sharedRCCall]presentCallViewController:self.callView];
    
    /**
     *  Boss 端再次挂上代理  为了走下面的代理方法
     */
    [[RCCall sharedRCCall].currentCallSession setDelegate:self];
    
    /**
     *  动态发起一个在线面试  并对其进行扣费
     */
    DDBossOnlineInterviewAlert *bossOnlineInterviewAlert = [DDBossOnlineInterviewAlert shareManager];
    
    bossOnlineInterviewAlert.emplyoerID = [DDLoginUserManager userID];
    
    NSString *jobfinderID = self.targetID;
    NSArray *arrayString = [jobfinderID componentsSeparatedByString:@"_"]; //从字符_中分隔成2个元素的数组  保存邀请只需要纯数字的id
    bossOnlineInterviewAlert.jobfinderID = [NSString stringWithFormat:@"%@",arrayString[0]];
    
    NSUserDefaults *savaJobIdUserDefaults = [NSUserDefaults standardUserDefaults];
    NSString *jobID = [savaJobIdUserDefaults objectForKey:[NSString stringWithFormat:@"%@To%@_employer_JobId",jobfinderID,[DDLoginUserManager userID]]];
    bossOnlineInterviewAlert.jobID = jobID;
    
    [bossOnlineInterviewAlert creatInterviewAndFeededuction];
    
}
- (void)callDidDisconnect
{
    /**
     *  视频通话结束
     */
    [[RCCall sharedRCCall]dismissCallViewController:self.callView];
    
    [[NSNotificationCenter defaultCenter] postNotificationName:NOTI_OnlineInterview_END object:self userInfo:nil];
    
    [[UIDevice currentDevice] setProximityMonitoringEnabled:NO];
    
}
- (void)remoteUserDidRing:(NSString *)userId
{
    
}
- (void)remoteUserDidInvite:(NSString *)userId
                  mediaType:(RCCallMediaType)mediaType
{
    
}
- (void)remoteUserDidJoin:(NSString *)userId
                mediaType:(RCCallMediaType)mediaType
{
    
}
- (void)remoteUserDidChangeMediaType:(NSString *)userId
                           mediaType:(RCCallMediaType)mediaType
{
    
}
- (void)remoteUserDidDisableCamera:(BOOL)disabled byUser:(NSString *)userId
{
    
}
- (void)remoteUserDidLeft:(NSString *)userId
                   reason:(RCCallDisconnectReason)reason
{
    
    [[RCCall sharedRCCall]dismissCallViewController:self.callViewPre];
    
    [[UIDevice currentDevice] setProximityMonitoringEnabled:NO];
    
}
- (void)shouldAlertForWaitingRemoteResponse
{
    
}
- (void)shouldRingForIncomingCall
{
    
}
- (void)shouldStopAlertAndRing
{
    
    [[RCCall sharedRCCall]dismissCallViewController:self.callViewPre];
    
    [[UIDevice currentDevice] setProximityMonitoringEnabled:NO];
    
}
- (void)errorDidOccur:(RCCallErrorCode)error
{
    /**
     *  视频通话错误
     */
    [[RCCall sharedRCCall]dismissCallViewController:self.callView];
    
    [[NSNotificationCenter defaultCenter] postNotificationName:NOTI_OnlineInterview_ERROR object:self userInfo:nil];
    
    [[UIDevice currentDevice] setProximityMonitoringEnabled:NO];
    
}
- (void)resultForStartServerRecording:(BOOL)startSuccess
                            errorCode:(RCCallErrorCode)errorCode
{
    
}

- (void)resultForStopServerRecording:(BOOL)stopSuccess
                           errorCode:(RCCallErrorCode)errorCode
{
    
}
- (void)resultForFetchServerRecordingStatus:(BOOL)fetchSuccess
                                     status:(BOOL)isRecording
                                  errorCode:(RCCallErrorCode)errorCode
{
    
}

- (void)dealloc
{
    [[NSNotificationCenter defaultCenter] removeObserver:self];
    
}
@end
